<?php

require_once 'User.php';

/*
    zend db table
*/
class Application_Model_DbTable_Users extends Zend_Db_Table_Abstract
{
    protected $_name = 'ap_user';
}




/*
    mapper
*/
class Users extends BaseMapper
{
    protected $_modelName   = 'User';
    protected $_dbTableName = 'Application_Model_DbTable_Users';

    //
    // access database
    //

    public function addUser( $model )
    {
        return $this->_save( $model, 'add' );
    }

    public function updateUser( $model )
    {
        return $this->_save( $model, 'update' );
    }

    public function getUser($id, $authType=NULL, $status=NULL )
    {
        $model = $this->_find($id);
        if( NULL                  !== $authType AND
            $model->getAuthType() !== $authType     )
        {
            return false;
        }
        if( NULL                !== $status AND
            $model->getStatus() !== $status     )
        {
            return false;
        }
        return $model;
    }

    public function getUserByAccount($account)
    {
        $where = $this->getDb()->getAdapter()->quoteInto(' account = ? ', $account);

        //$order = 'favorite_color';
        //$row = $table->fetchRow($where, $order);

        $row = $this->getDb()->fetchRow($where);
        if (0 == count($row)) {
            return false;
        }
        return $this->mapRow( $row->toArray() );
    }

    public function getUserByAuthenticate($account,$password)
    {
        $model = $this->getModel();
        $model->setPassword($password);

        $where = $this->getDb()->getAdapter()->quoteInto('     account  = ? ', $account)
               . $this->getDb()->getAdapter()->quoteInto(' AND password = ? ', $model->getPassword() );

        $row = $this->getDb()->fetchRow($where);
        if (0 == count($row)) {
            return false;
        }
        return $this->mapRow( $row->toArray() );
    }

    public function getUsers( $searchKey='', $page=1, $rowCount=BaseMapper::DEFAULT_ROW_COUNT ) 
    {
        $opt = Array(
            '_orderBy'   => ' id ASC ',
            '_searchKey' => $searchKey,
            '_page'      => $page,
            '_rowCount'  => $rowCount,
        );
        return $this->_getByQuery($opt);
    }
    public function getCountByUsers( $searchKey='' ) 
    {
        $opt = Array(
            '_searchKey' => $searchKey,
        );
        return $this->_getByQuery($opt,true);
    }

    protected function _getByQuery( $opt, $isGetTotal=false )
    {
        $this->_checkOption($opt);
        $opt += Array(
            'id'            => (ISSET($opt['id'])               ? (int) ($opt['id'])                : NULL ),
            'account'       => (ISSET($opt['account'])          ?       ($opt['account'])           : NULL ),
            'password'      => (ISSET($opt['password'])         ?       ($opt['password'])          : NULL ),
            'authMethod'    => (ISSET($opt['authMethod'])       ?       ($opt['authMethod'])        : NULL ),
            'authType'      => (ISSET($opt['authType'])         ? (int) ($opt['authType'])          : NULL ),
            'email'         => (ISSET($opt['email'])            ?       ($opt['email'])             : NULL ),
            'emailStatus'   => (ISSET($opt['emailStatus'])      ? (int) ($opt['emailStatus'])       : NULL ),
            'createDate'    => (ISSET($opt['createDate'])       ?       ($opt['createDate'])        : NULL ),
            'updateDate'    => (ISSET($opt['updateDate'])       ?       ($opt['updateDate'])        : NULL ),
            'properties'    => (ISSET($opt['properties'])       ?       ($opt['properties'])        : NULL ),

            '_searchKey'    => (ISSET($opt['_searchKey'])       ?       ($opt['_searchKey'])        : NULL ),
            '_orderBy'      => (ISSET($opt['_orderBy'])         ?       ($opt['_orderBy'])          : ' id DESC ' ),
            '_page'         => (ISSET($opt['_page'])            ? (int) ($opt['_page'])             : 1 ),
            '_rowCount'     => (ISSET($opt['_rowCount'])        ? (int) ($opt['_rowCount'])         : BaseMapper::DEFAULT_ROW_COUNT ),
        );

        if( isset($opt['_page']) && $opt['_page']<=1 ) {
            $opt['_page'] = 1;
        }


        $where = Array();
        if(isset($opt['id']          )) { $where[] = $this->getDb()->getAdapter()->quoteInto('id = ?',           $opt['id']          );  }
        if(isset($opt['account']     )) { $where[] = $this->getDb()->getAdapter()->quoteInto('account = ?',      $opt['account']     );  }
        if(isset($opt['password']    )) { $where[] = $this->getDb()->getAdapter()->quoteInto('password = ?',     $opt['password']    );  }
        if(isset($opt['authMethod']  )) { $where[] = $this->getDb()->getAdapter()->quoteInto('auth_method = ?',  $opt['authMethod']  );  }
        if(isset($opt['authType']    )) { $where[] = $this->getDb()->getAdapter()->quoteInto('auth_type = ?',    $opt['authType']    );  }
        if(isset($opt['email']       )) { $where[] = $this->getDb()->getAdapter()->quoteInto('email = ?',        $opt['email']       );  }
        if(isset($opt['emailStatus'] )) { $where[] = $this->getDb()->getAdapter()->quoteInto('email_status = ?', $opt['emailStatus'] );  }
        if(isset($opt['createDate']  )) { $where[] = $this->getDb()->getAdapter()->quoteInto('create_date = ?',  $opt['createDate']  );  }
        if(isset($opt['updateDate']  )) { $where[] = $this->getDb()->getAdapter()->quoteInto('update_date = ?',  $opt['updateDate']  );  }
        if(isset($opt['properties']  )) { $where[] = $this->getDb()->getAdapter()->quoteInto('properties = ?',   $opt['properties']  );  }

        if(isset($opt['_searchKey'])) {
            // 注意: 特殊符號應該要變更一下 => "%" "_" 之類的
            $searchTerms[] = $this->getDb()->getAdapter()->quoteInto('email LIKE ?',        '%'.$opt['_searchKey'].'%' );
          //$searchTerms[] = $this->getDb()->getAdapter()->quoteInto('properties LIKE ?',   '%'.$opt['_searchKey'].'%' );
            $where[] = join(' OR ',$searchTerms);
        }

        //
        if( $isGetTotal ) {
            $select = $this->getDb()->select();
            $select
                ->from( $this->getDb(), Array('COUNT(id) AS total') )
                ->where( join(' AND ',$where) );
            $rows = $this->getDb()->fetchRow($select);
            $row = $rows->toArray();
            return (int) $row['total'];
        }

        //
        //echo join(' AND ',$where); exit;

        //
        if( NULL === $opt['_page'] ) {
            $rowset = $this->getDb()->fetchAll(join(' AND ',$where), $opt['_orderBy']);
        }
        else {
            $offset = ($opt['_page']-1) * $opt['_rowCount'];
            $rowset = $this->getDb()->fetchAll(join(' AND ',$where), $opt['_orderBy'], $opt['_rowCount'], $offset );
        }
        if( !$rowset ) {
            return NULL;
        }

        $models = Array();
        foreach( $rowset as $row ) {
            $models[] = $this->mapRow( $row->toArray() );
        }
        return $models;
    }

    //================================================================================
    // about model object
    //================================================================================

    public function mapRow($row)
    {
        //properties
        is_array($row["properties"])
            ? $row["properties"] = unserialize($row["properties"])
            : $row["properties"] = Array();

        $model = $this->getModel();
        $model->setId                 ( $row['id']            );
        $model->setAccount            ( $row['account']       );
        $model->setPurePassword       ( $row["password"]      );
        $model->setAuthMethod         ( $row['auth_method']   );
        $model->setAuthType           ( $row['auth_type']     );
        $model->setEmail              ( $row['email']         );
        $model->setEmailStatus        ( $row['email_status']  );
        $model->setStatus             ( $row['status']        );
        $model->setCreateDate         ( strtotime($row['create_date'])   );
        $model->setUpdateDate         ( strtotime($row['update_date'])   );
        $model->setProperties         ( $row['properties']    );
        return $model;
    }

}
